package com.laike.pay.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.laike.pay.R;
import com.laike.pay.adapter.PayAdapter;
import com.laike.pay.baifuprint.PrinterUtil;
import com.laike.pay.base.BaseActivity;
import com.laike.pay.base.MyApplication;
import com.laike.pay.bean.PayOrder;
import com.laike.pay.http.BaseCallback;
import com.laike.pay.http.ParamsUtils;
import com.laike.pay.http.Result;
import com.laike.pay.http.api.ApiName;
import com.laike.pay.utils.DateUtils;
import com.laike.pay.utils.GreenDaoManager;
import com.laike.pay.utils.SharedPreferencesUtils;
import com.laike.pay.utils.TimeUtils;
import com.laike.pay.utils.ToastUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Response;


public class TransactionActivity extends BaseActivity implements BaseCallback<Result<Map<String, Object>>> {

    @Bind(R.id.serach)
    TextView serach;
    private Button bt_print;
    private ListView list_detail;
    private TextView et_starttime;
    private TextView et_endtime;
    private TextView et_state;
    private TextView dealMoneySum;//交易总额
    private TextView dealCount;//交易笔数
    private PayAdapter adapter;
    private Intent intent = null;
    private RelativeLayout title;
    private int pageIndex = 1;
    private int pageNum = 10;
    List<String> list;
    private PopupWindow popupWindow;
    List<PayOrder> orders;
    String sumMoney;
    String count;
    private Calendar c = Calendar.getInstance();
    private int indexType = 0;
    private static final String PAY_TYPE = "22";// 刷卡类型

    @Override
    public int getContentViewResId() {
        return R.layout.activity_detail;
    }
    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void intiViews() {
        list = new ArrayList<>();
        list.add(0, "已支付");
        list.add(1, "已退款");
        list.add(2, "未支付");
        serach.setVisibility(View.VISIBLE);
        serach.setOnClickListener(this);
        dealMoneySum = (TextView) findViewById(R.id.total_tt);
        dealCount = (TextView) findViewById(R.id.count_tt);
        title = (RelativeLayout) findViewById(R.id.title);
        list_detail = (ListView) findViewById(R.id.detail_list);
        list_detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                intent = new Intent(TransactionActivity.this, DealDetailsActivity.class);
                PayOrder po = (PayOrder) adapter.getItem(i);
                intent.putExtra("order", po);
                String pay_type=po.getPay_type();
                intent.putExtra("index","22".endsWith(pay_type)?1:0);
                startActivity(intent);
            }
        });
        list_detail.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (null == orders || absListView.getCount() < pageNum) {
                    return;
                }
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        if (indexType == 1) {//表示刷卡明细
                            getBrushAllOrder();
                        } else {
                            MyApplication.getSerivceApi().getAllOrder(SharedPreferencesUtils.getAppid(),
                                    ApiName.GET_ALL_ORDER, ParamsUtils.getAllOrder("", "", pageIndex + "", pageNum + "", "1", ""), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId(),
                                    "", "", pageIndex + "", pageNum + "", "1").enqueue(TransactionActivity.this);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });
        bt_print = (Button) findViewById(R.id.print_bt);
        bt_print.setOnClickListener(this);
        TextView tv = (TextView) findViewById(R.id.statistical_time);
        String month = ((c.get(Calendar.MONTH) + 1) < 10 ? "0" + (c.get(Calendar.MONTH) + 1) : (c.get(Calendar.MONTH) + 1)) + "";
        String day = c.get(Calendar.DATE) < 10 ? "0" + c.get(Calendar.DATE) : c.get(Calendar.DATE) + "";
        tv.setText(c.get(Calendar.YEAR) + "-" + month + "-" + day);
        bindView();
    }

    @Override
    public String setTitle() {
        return  getIntent().getIntExtra("pay_type", 0)==1?"刷卡统计":getString(R.string.sum_today);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    public void initmPopupWindowView() {
        //获取自定义布局文件pop.xml的视图
        View customView = getLayoutInflater().inflate(R.layout.pop_search, null);
        popupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        et_starttime = (TextView) customView.findViewById(R.id.start_time);
        et_starttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimeChoose(et_starttime);
            }
        });
        et_endtime = (TextView) customView.findViewById(R.id.end_time);
        et_endtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimeChoose(et_endtime);
            }
        });
        et_state = (TextView) customView.findViewById(R.id.status);
        et_state.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showOption(et_state, list);
            }
        });
        TextView search = (TextView) customView.findViewById(R.id.serach_bt);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(TransactionActivity.this, SearchResultAtivity.class);
                intent.putExtra("pay_type", indexType);
                String startTime = et_starttime.getText().toString();
                String endTime = et_endtime.getText().toString();
                String statusValue = et_state.getText().toString();
                //如果都没有选择
                if (startTime.equals("") && endTime.equals("") && statusValue.equals("")) {
                    return;
                }
                if (!endTime.equals("") && startTime.equals("")) {
                    ToastUtils.showToast(TransactionActivity.this, "请选择开始时间", 2000);
                    return;
                }
                if (endTime.equals("") && !startTime.equals("")) {
                    ToastUtils.showToast(TransactionActivity.this, "请选择结束时间", 2000);
                    return;
                }
                //开始时间小于结束时间
                try {
                    if (DateUtils.stringToDate(startTime, endTime)) {
                        intent.putExtra("startTime", startTime);
                        intent.putExtra("endTime", endTime);
                    } else {
                        ToastUtils.showToast(TransactionActivity.this, "结束时间必须大于开始时间", 2000);
                        return;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (!statusValue.equals("")) {
                    String payStatus = "";
                    if (statusValue.equals(list.get(0))) {
                        payStatus = "1";
                    } else if (statusValue.equals(list.get(1))) {
                        payStatus = "-1";
                    } else if (statusValue.equals(list.get(2))) {
                        payStatus = "0";
                    }
                    intent.putExtra("status", payStatus);
                }
                et_state.setText("");
                et_starttime.setText("");
                et_endtime.setText("");
                popupWindow.dismiss();
                startActivity(intent);

            }
        });
        popupWindow.showAsDropDown(title);
        popupWindow.getContentView().

                setFocusableInTouchMode(true);
        popupWindow.getContentView().
                setFocusable(true);
        popupWindow.getContentView().
                setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() ==
                                0 && event.getAction() == KeyEvent.ACTION_DOWN) {
                            if (popupWindow != null && popupWindow.isShowing()) {

                                popupWindow.dismiss();
                                return true;
                            }
                            return false;
                        }
                        return false;
                    }
                });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        switch (id) {
            case R.id.print_bt:
                doPrint();
                break;
            case R.id.serach:
                initmPopupWindowView();
                break;
        }
    }

    OptionsPickerView pvCustomOptions;

    /**
     * 条件选择
     */

    private void showOption(final TextView tv, final List<String> list) {
        // 注意：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针
        // 具体可参考demo 里面的两个自定义布局
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tv.setText(list.get(options1));
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.returnData();
                                pvCustomOptions.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.dismiss();
                            }
                        });

                    }
                }).setContentTextSize(20)
                .isDialog(true)
                .build();
        pvCustomOptions.setPicker(list);//添加数据
        pvCustomOptions.show();
    }

    TimePickerView pvTime;

    /**
     * 时间选择器
     *
     * @param tv
     */
    private void showTimeChoose(final TextView tv) {
        if (null != pvTime) {
            pvTime.dismiss();
        }
        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tv.setText(TimeUtils.stampToDate(date.getTime() + "", "yyyy-MM-dd HH:mm:ss"));

            }
        }).isDialog(true)
                .setContentSize(16)
                .build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，
        // 避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.setDate(Calendar.getInstance());
        pvTime.show();
    }

    //打印今日数据
    private void doPrint() {
        if (null == orders || orders.size() == 0) {
            ToastUtils.showToast(this, getString(R.string.no_have_data), 3000);
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                PrinterUtil printer = new PrinterUtil(TransactionActivity.this);
                try{
                    printer.printTransaction(orders, count, sumMoney);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 绑定方法
     */
    public void bindView() {
        adapter = new PayAdapter(this);
        list_detail.setAdapter(adapter);
        Intent intent = getIntent();
        if (null != intent) {
            indexType = intent.getIntExtra("pay_type", 0);
        }
        if (indexType == 1) {//表示刷卡明细
            getBrushAllOrder();
        } else {//表示扫码明细和刷卡明细
            if (onNetChange()) {//手机有连接到网络
                bt_print.setVisibility(View.VISIBLE);
                MyApplication.getSerivceApi().getAllOrder(SharedPreferencesUtils.getAppid(),
                        ApiName.GET_ALL_ORDER, ParamsUtils.getAllOrder("", "", pageIndex + "", pageNum + "", "1", ""), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId(),
                        "", "", pageIndex + "", pageNum + "", "1").enqueue(this);
            } else {
                List<PayOrder> orders = GreenDaoManager.getInstance().getNewSession().getPayOrderDao().loadAll();
                this.orders = orders;
                adapter.setData(orders);
                bt_print.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 查询刷卡明细的请求
     */
    private void getBrushAllOrder() {
        MyApplication.getSerivceApi().getBrushAllOrder(SharedPreferencesUtils.getAppid(),
                ApiName.GET_ALL_ORDER, ParamsUtils.getAllOrder("", "", pageIndex + "", pageNum + "", "1", PAY_TYPE), SharedPreferencesUtils.getTerminalNumber(), SharedPreferencesUtils.getWorkMenId(),
                "", "", pageIndex + "", pageNum + "", "1", PAY_TYPE).enqueue(this);
    }
    @Override
    public void onResponse(Call<Result<Map<String, Object>>> call, Response<Result<Map<String, Object>>> response) {
        if (response.code() == 200) {
            if (response.body().getStatus().equals("1")) {
                List<Map<String, String>> payOrders = (List<Map<String, String>>) response.body().getResult().get("list");
                if (null == payOrders || payOrders.size() == 0) {
                    ToastUtils.showToast(TransactionActivity.this, "没有数据", 3000);
                    return;
                }
                orders = mapToPayorder(payOrders);
                adapter.setData(orders);
                sumMoney = response.body().getResult().get("today_count_amount").toString();
                count = response.body().getResult().get("today_count_order").toString();
                dealMoneySum.setText(getString(R.string.today_deal_sum, sumMoney));
                dealCount.setText(getString(R.string.today_deal_count, ((int) Double.parseDouble(count)) + ""));
                pageIndex++;
            }
        }
    }

    @Override
    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
        Log.v("onFailure", "error message" + t.getMessage());
    }

    private List<PayOrder> mapToPayorder(List<Map<String, String>> data) {
        List<PayOrder> list = new ArrayList<>();
        int length = data.size();
        PayOrder po = null;
        for (int i = 0; i < length; i++) {
            po = new PayOrder();
            po.setOut_trade_no(data.get(i).get("out_trade_no"));
            po.setBody(data.get(i).get("body"));
            po.setUid(data.get(i).get("uid"));
            po.setTrade_no(data.get(i).get("trade_no"));
            po.setService(data.get(i).get("service"));
            po.setProduct_id(data.get(i).get("product_id"));
            po.setPay_type(data.get(i).get("pay_type"));
            po.setTotal_amount(data.get(i).get("total_amount"));
            po.setDiscountable_amount(data.get(i).get("discountable_amount"));
            po.setPay_amount(data.get(i).get("pay_amount"));
            po.setUid(data.get(i).get("pay_uid"));
            po.setShop_id(data.get(i).get("shop_id"));
            po.setTerminal_id(data.get(i).get("terminal_id"));
            po.setAgent_uid(data.get(i).get("agent_uid"));
            po.setWorkmen_id(data.get(i).get("workmen_uid"));
            po.setStatus(data.get(i).get("status"));
            po.setPaytime(data.get(i).get("paytime"));
            po.setAddtime(data.get(i).get("addtime"));
            po.setUptime(data.get(i).get("uptime"));
            po.setPay_name(data.get(i).get("pay_name"));
            list.add(po);
        }
        return list;
    }
}
